var ERROR = {
		bgColor: '#F8E0F7',
		addArr: function($data){
			for($i = 0; $i < $data.length;  $i++){
				$('div.errors ul').append('<li>'+$data[i]+'</li>');
			}
		},
		add: function($data){
			$('div.errors ul').append('<li>'+$data+'</li>');
		},
		clear: function(){
			$('div.errors ul').html('');
		},
		show: function(){
			$('div.errors').show('fast');
		},
		hide: function(){
			$('div.errors').hide('fast');
		}
};
var LOADING = {
		isLoading: false,
		show: function(){
			$('div.hz-loading').show();
			LOADING.isLoading = true;
		},
		hide: function(){
			$('div.hz-loading').hide();
			LOADING.isLoading = false;
		}
}
var ADMIN = {
		uploadPath: '/uploads/',
		uploadEmpty: '/css/admin/img/global/no-img.png',
		isLeftShow: true,
		isTopShow: false,
		paddingLeft: 22,
		paddingTop: 55,
		init:function(){
			ADMIN.common();
			ADMIN.initMenu();
			ADMIN.setDefault();
		},
		settings:function(){
			if(ADMIN.isLeftShow){
				ADMIN.paddingLeft = 22;
			}else{
				ADMIN.paddingLeft = 42;
			}
			var heightTop = 0;
			//heightTop = parseInt($('div#page-top').height(),10);
			
			var height = parseInt($(window).height(), 10) - ADMIN.paddingTop - heightTop;
			var widthLeft = parseInt($('#page-content-left').width(),10);
			var left = parseInt($(window).width(), 10) - widthLeft - ADMIN.paddingLeft - 10;
			
			
			
			$('#page-content-left > #inner').attr('style','height:'+ height +'px');
			$('#page-content-right > #inner').attr('style','height:' + height +'px;width:'+ left +'px');
			
		},
		
		initMenu:function(){
			$('#page-content-left .box-menu .title').click(function(){
				$(this).next().slideToggle('fast');
				if($(this).attr('class').indexOf('title-unactive')>0){
					$(this).removeClass('title-unactive');
					$(this).attr('title',ADMIN.boxTitleCollapse);
				}else{
					$(this).addClass('title-unactive');
					$(this).attr('title',ADMIN.boxTitleExpand);
				}
			});
		},
		common: function(){
			ADMIN.settings();
			$('#page-content-left #control-show').unbind('click').click(function(){
				var $left = $('#page-content-left');
				if(ADMIN.isLeftShow){
					$left.css('width','10px');
					ADMIN.isLeftShow = false;
					$('div.mCSB_dragger_bar', $left).hide();
					$(this).css('left','2px').html('&raquo;');
				}else{
					$left.css('width','250px');
					ADMIN.isLeftShow = true;
					$('div.mCSB_dragger_bar', $left).show();
					$(this).css('left','252px').html('&laquo;');
				}
				ADMIN.settings();
				ADMIN.settings();
			});
			$('#page-content-left > #inner, #page-content-right > #inner').mCustomScrollbar({
				scrollButtons:{
					enable:false
				},
				scrollInertia:150,
				advanced:{
					updateOnBrowserResize:true, 
					updateOnContentResize:true, 
					autoExpandHorizontalScroll:false 
				}
			});
			
			$(window).resize(function(){
				ADMIN.settings();
				ADMIN.settings();
			});
			
		},
		setDefault: function(){
			
			$.datepicker.setDefaults({
				showOn: "button",
				buttonImageOnly: true,
				buttonImage: "/css/admin/img/global/calendar-icon.jpg",
				buttonText: "Lịch",
				showButtonPanel: true,
				changeMonth: true,
				changeYear: true
			});
			$.datepicker.regional['vn'] = {clearText: 'Xoá', clearStatus: '',
					closeText: 'Hoàn thành', closeStatus: 'Hoàn thành',
					prevText: '<Trước', prevStatus: 'tháng trước',
					nextText: 'Sau>', nextStatus: 'tháng kế tiếp',
					currentText: 'Hôm nay', currentStatus: 'Ngày hôm nay',
					monthNames: ['Tháng 1','Tháng 2','Tháng 3','Tháng 4','Tháng 5','Tháng 6','Tháng 7','Tháng 8','Tháng 9','Tháng 10','Tháng 11','Tháng 12'],
					monthNamesShort: ['1','2','3','4','5','6','7','8','9','10','11','12'],
					monthStatus: 'Tháng sau', yearStatus: 'Năm sau',
					weekHeader: 'Tuần', weekStatus: '',
					dayNames: ['Chủ nhật','Thứ 2','Thứ 3','Thứ 4','Thứ 5','Thứ 6','Thứ 7'],
					dayNamesShort: ['CN','Hai','Ba','Tu','Nam','Sáu','Bảy'],
					dayNamesMin: ['CN','2','3','4','5','6','7'],
					dayStatus: 'Ngày đầu tuần', dateStatus: 'Chọn ngày',
					dateFormat: 'dd/mm/yy', firstDay: 0, 
					initStatus: 'Chọn ngày', isRTL: false};
			$.datepicker.setDefaults( $.datepicker.regional[ "vn" ] );
			$('input.date-picker-month').datepicker({ 
				dateFormat: 'mm/yy',
				onClose: function(dateText, inst) { 
					var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
					var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
					$(this).datepicker('setDate', new Date(year, month, 1));
				},
				beforeShow : function(input, inst) {
					if ((datestr = $(this).val()).length > 0) {
						year = datestr.substring(3, datestr.length);
						month = datestr.substring(0, 2);
						$(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
						$(this).datepicker('setDate', new Date(year, month-1, 1));
					}
				}
			});
			$('input.date-picker').datepicker();
			$('div.tabs').tabs();
			$('textarea.editor').each(function(){
				CKEDITOR.replace($(this).attr('id'),{
					filebrowserBrowseUrl : '/admin/uploadControl/ckeditor',
				});
			});
			
			$('input.number').keydown(function(event) {
				// Allow: backspace, delete, tab, escape, and enter,  Ctrl+A, home, end, left, right
				if ( event.keyCode ==190 
						||  event.keyCode == 46 
						|| event.keyCode == 8 
						|| event.keyCode == 9 
						|| event.keyCode == 27 
						|| event.keyCode == 13 
						|| (event.keyCode == 65 && event.ctrlKey === true) 
						|| (event.keyCode == 86 && event.ctrlKey === true) 
						|| (event.keyCode >= 35 && event.keyCode <= 39)) {
					return;
					
				}
				else {
					// Ensure that it is a number and stop the keypress
					if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
						event.preventDefault(); 
					}
				}
			});
			
			$('select.hz-selected').each(function(){
				var $ob = $(this);
				if($ob.attr('data-selected')){
					$ob.val($ob.attr('data-selected'));
				}
			});
			
			$('input.hz-data-sample, textarea.hz-data-sample').each(function(){
				var $ob = $(this);
				if($ob.val() == ''){
					$ob.val($ob.attr('data-sample'));
				}
				$ob.focus(function(){
					if($ob.val() == $ob.attr('data-sample')){
						$ob.val('');
					}
				});
				$ob.blur(function(){
					if($ob.val() == ''){
						$ob.val($ob.attr('data-sample'));
					}
				});
			});
			
			$('input.chk-checkall').unbind('click').click(function(){
				$('input.checkbox-select').prop('checked',$(this).is(':checked'))
			});
			$('input.checkbox-select').unbind('click').click(function(){
				$('input.chk-checkall').prop('checked', $('input.checkbox-select:checked').length == $('input.checkbox-select').length);
			});
			
			
			$('select.hz-refer-to').each(function(){
				var $ob = $(this);
				$ob.val($('#'+$ob.attr('data-refer')).val());
				$ob.unbind('change').change(function(){
					$('#'+$(this).attr('data-refer')).val($(this).val());
				});
			});
			$('select.hz-refer-update-select').each(function(){
				var $ob = $(this);
				$ob.unbind('change').change(function(){
					$('select#'+$ob.attr('data-refer')).html('<option value="-1">...loading...</option>');
					$.ajax({
						type: "POST",
						url: $ob.attr('data-url'),
						data: {
							cate_id: $ob.val(),
							action_name: $ob.attr('data-action')
						},
						cache: false,
						success: function(data){
							var $data = $.parseJSON(data);
							if($data.status==1){
								var $str='<option value="-1" selected>'+$ob.attr('data-text')+'</option>';
								if($data.data.length){
									for(var i=0; i<$data.data.length; i++){
										$str+='<option value="'+$data.data[i].id+'">'+$data.data[i].name+'</option>';
									}
								}
								$('select#'+$ob.attr('data-refer')).html('').append($str).val($ob.attr('data-value')).trigger('change');
							}else{
								alert('Error when trying connect to server. Contact with vcqviet@gmail.com');
							}
						}
					});
				});
				$ob.trigger('change');
			});
			
			ADMIN.addUpload();
			ADMIN.setIsDefault();
			ADMIN.controlAction();
			ADMIN.filter();
			ADMIN.formRequire();
			
		},
		
		filter: function(){
			$('a.hz-filter-submit, input.hz-filter-submit, img.hz-filter-submit').unbind('click').click(function(){
				var $ob = $(this);
				var $filter = $('#'+$ob.attr('data-keysearch-id'));
				var $form = $('#'+$ob.attr('data-form-id'));
				if($filter.val() == $filter.attr('data-sample')){
					$filter.val('');
				}
				$form.submit();
				return false;
			});
		},
		controlAction: function(){
			$('a.hz-control, input.hz-control, img.hz-control').css('cursor','pointer').click(function(){
				var $ob = $(this);
				var $isError = false;
				ERROR.clear();
				if($ob.attr('hz-require')=='selected'){
					if($('input.checkbox-select:checked').length <= 0){
						$isError = true;
						ERROR.add($('div.errors').attr('error-row-select'));
						ERROR.show();
					}
				}
				
				if(!$isError){
					ERROR.hide();
					if($(this).attr('hz-confirm')=='confirm'){
						if(!confirm($(this).attr('data-confirm'))){
							return false;
						}
					}
					$('#action-name').val($ob.attr('data-action'));
					$('#form-main').submit();
				}else{
					ERROR.show();
				}
				
				return false;
			});
			
			$('a.hz-control-get, input.hz-control-get, img.hz-control-get').css('cursor','pointer').click(function(){
				$(this).attr('href',$('#form-main').attr('action')+'&action_name='+$(this).attr('data-action'));
				return true;
			});
			$('a.hz-control-ajax, input.hz-control-ajax, img.hz-control-ajax, button.hz-control-ajax').css('cursor','pointer').click(function(){
				if(LOADING.isLoading) return false;
				LOADING.show();
				var $ob = $(this);
				ERROR.clear();
				try{
					var $fn = window[$ob.attr('callback-before-send')];
					if(typeof ($fn) === 'function'){
						$fn();
					}
				}catch(ex){
					
				};
				$.ajax({
					type: "POST",
					url: $ob.attr('data-url'),
					data: {
						val: $ob.attr('data-value'),
						id: $ob.attr('data-id'),
						action_name: $ob.attr('data-action')
					},
					cache: false,
					success: function(data){
						LOADING.hide();
						try{
							var $fn = window[$ob.attr('callback-after-success')];
							if(typeof ($fn) === 'function'){
								$fn(data);
							}
						}catch(ex){
							
						};
					}
				});
			});
			$('a.hz-submit, input.hz-submit, img.hz-submit').unbind('click').click(function(){
				var $ob = $(this);
				var $form = $('#'+$ob.attr('data-form-id'));
				if(ADMIN.formCheck()){
					$form.submit();
				}
				return false;
			});
		},
		addUpload: function(){
			$('input.upload-photo').each(function(){
				var $ob = $(this);
				var $img = $('<img src="'+ADMIN.uploadEmpty+'" class="upload-preview" data-id="'+$ob.attr('id')+'"/>');
				var $a = '';
				if($ob.val().trim().length > 0){
					$img.attr('src', $ob.val());
					$a = '<a href="#" class="upload-remove"></a>';
				}
				$ob.parent().append($img).append($a);
			});
			ADMIN.addUploadDocument();
			ADMIN.addUploadPhoto();
			ADMIN.removeUploadPhoto();
			ADMIN.removeDocument();
			
		},
		addUploadPhoto: function(){
			$('input.data-checkbox').each(function(){
				if(this.checked){
					$('input#'+$(this).attr('data-name')).val($(this).val());
				}
			});
			$('img.upload-preview').uploadControl({
				file_type: 'jpg|jpeg|png|gif|swf',
				path: 'all',
				language: 'vi',
				max_depth: 0,
				buttons:'upload|select|remove|rename|reload|mkdir|language',
				callback:{
					beforeSelect: function(selectedFile, currentControl){},
					afterSelected: function(selectedFile, currentControl){},
					onClosed: function(selectedFile, currentControl){
						if(selectedFile){
							$('input#'+currentControl.attr('data-id')).val(ADMIN.uploadPath+selectedFile.path);
							$('a.upload-remove').remove();
							var oA = $('<a href="#" class="upload-remove"></a>');
							var arr = selectedFile.path.toString().split('.');
							if(arr.length>=2 && arr[arr.length-1].toString().toLowerCase()=='swf'){
								currentControl.attr('src',ADMIN.uploadEmpty);
								$('div.not-click', currentControl.parent().parent()).parent().remove();
								var pr = currentControl.parent();
								var str = ULTI.printSWF({
									width: '100',
									height: '80',
									path: ADMIN.uploadPath + selectedFile.path,
									flashvars: '',
									wmode: 'transparent',
									divclass: 'not-click'
								});
								var swf = $('<span class="img-item">'+str+'</span>');
								swf.append(oA);
								pr.parent().append(swf);
							}else{
								currentControl.attr('src',ADMIN.uploadPath+selectedFile.path);
								currentControl.parent().append(oA);
							}
							ADMIN.removeUploadPhoto();
						}
					}
				}
			});
			$('img.upload-preview-multi').uploadControl({
				file_type: 'jpg|jpeg|png',
				path: 'all',
				language: 'vi',
				max_depth: 0,
				buttons:'upload|select|remove|rename|reload|mkdir|language',
				callback:{
					beforeSelect: function(selectedFile, currentControl){},
					afterSelected: function(selectedFile, currentControl){},
					onClosed: function(selectedFile, currentControl){
						if(selectedFile){
							var oSpan = $('<span class="img-item"></span>');
							var oInput= $('<input type="hidden" name="'+currentControl.attr('data-name')+'[]" value="'+(ADMIN.uploadPath+selectedFile.path)+'"/>');
							var oImg = $('<img class="upload-preview-multi" src="'+ADMIN.uploadPath+selectedFile.path+'"/>');
							var oA = $('<a href="#" class="upload-remove-multi" title="remove" alt="remove"></a>');
							oSpan.append(oInput);
							oSpan.append(oImg);
							if(currentControl.attr('data-checkbox')){
								var oChk = $('<input type="checkbox" name="'+currentControl.attr('data-checkbox')+'[]" data-name="'+currentControl.attr('data-checkbox-name')+'" class="data-checkbox" value="'+(ADMIN.uploadPath+selectedFile.path)+'" title="set default" alt="set default" />');
								oSpan.append(oChk);
							}
							oSpan.append(oA);
							currentControl.parent().parent().append(oSpan);
							ADMIN.removeUploadPhoto();
							ADMIN.setIsDefault();
						}
					}
				}
			});
		},
		removeUploadPhoto: function(){
			$('a.upload-remove').unbind('click').click(function(){
				var $img = $(this).prev('img');
				$img.attr('src',ADMIN.uploadEmpty);
				$('#'+$img.attr('data-id')).val('');
				$(this).remove();
				
				return false;
			});
			$('a.upload-remove-multi').unbind('click').click(function(){
				$(this).parent().remove();
				return false;
			});
		},
		addUploadDocument: function(){
			$('a.multi-documents-add').uploadControl({
				file_type: 'txt|pdf|doc|docx|xls|xlsx|ppt|pptx|eps|zip|rar',
				path: 'all',
				language: 'vi',
				max_depth: 0,
				buttons:'upload|select|remove|rename|reload|mkdir|language',
				callback:{
					beforeSelect: function(selectedFile, currentControl){},
					afterSelected: function(selectedFile, currentControl){},
					onClosed: function(selectedFile, currentControl){
						if(selectedFile){
							var $str = '<span class="documents-item">'
								+ '<input type="hidden" name="'+currentControl.attr('data-name')+'[]" value="'+(ADMIN.uploadPath+selectedFile.path)+'"/>'
								+ '<br/><span class="multi-documents-filename">'+selectedFile.name+'</span> &nbsp;'
								+ '<a href="#" class="multi-documents-remove" title="remove" alt="remove"></a>'
								+ '</span>';
							currentControl.parent().append($str);
							ADMIN.removeDocument();
						}
					}
				}
			});
		},
		removeDocument: function(){
			$('a.multi-documents-remove').unbind('click').click(function(){
				$(this).parent().remove();
			});
			return false;
		},
		setIsDefault: function(){
			$('input.data-checkbox').click(function(){
				$('input.data-checkbox').attr('checked', false);
				$(this).attr('checked', true);
				$('input#'+$(this).attr('data-name')).val($(this).val());
			});
		},
		
		formRequire: function(){
			$('.hz-required').each(function(){
				var $ob = $(this).parent().parent();
				$('.label', $ob).append('<span style="color:#f00;padding-left: 5px;">*</span>');
			});
			$('.hz-img-required').each(function(){
				var $ob = $(this).parent().parent().parent();
				$('.label', $ob).append('<span style="color:#f00;padding-left: 5px;">*</span>');
			});
		},
		formCheck: function(){
			var $isError = false;
			ERROR.clear();
			$('input.hz-required, textarea.hz-required').each(function(){
				var $ob = $(this);
				$ob.css('background','');
				
				if($ob.val()==''){
					$isError = true;
					$ob.css('background',ERROR.bgColor);
					ERROR.add($('div.errors').attr('error-empty'));
				}
			});
			$('input.hz-email').each(function(){
				var $ob = $(this);
				$ob.css('background','');
				
				if($ob.val()!='' && !VALIDATOR.isEmail($ob.val())){
					$isError = true;
					$ob.css('background',ERROR.bgColor);
					ERROR.add($('div.errors').attr('error-email'));
				}
				if($ob.hasClass('hz-required') && $ob.val()==''){
					$ob.css('background',ERROR.bgColor);
				}
			});
			$('input.hz-img-required').each(function(){
				var $ob = $(this);
				$ob.parent().parent().css('background','');
				
				if($ob.val().trim()==''){
					$isError = true;
					$ob.parent().parent().css('background',ERROR.bgColor);
					ERROR.add($('div.errors').attr('error-img-empty'));
				}
			});
			$('select.hz-required').each(function(){
				var $ob = $(this);
				$ob.css('background','');
				
				if($ob.val() == '' || parseInt($ob.val(),10) < 0 ){
					$isError = true;
					$ob.css('background',ERROR.bgColor);
					ERROR.add($('div.errors').attr('error-select'));
				}
			});
			$('input.hz-confirm-required').each(function(){
				var $ob = $(this);
				var $obc = $('#'+$ob.attr('data-id-confirm'));
				if($ob.val()=='' || $obc.val()=='') return;
				$ob.css('background','');
				$obc.css('background','');
				
				if($ob.val() != $obc.val()){
					$isError = true;
					$ob.css('background',ERROR.bgColor);
					$obc.css('background',ERROR.bgColor);
					ERROR.add($('div.errors').attr('error-confirm-required'));
				}
				if($ob.hasClass('hz-required') && $ob.val()==''){
					$ob.css('background',ERROR.bgColor);
				}
			});
			if($isError){
				ERROR.show();
			}else{
				ERROR.hide();
			}
			return !$isError;
		}
}